package com.jt.www.admin.market.controller;

import com.github.pagehelper.PageInfo;
import com.jt.www.admin.market.service.MarketerInfoService;
import com.jt.www.domain.bo.MarketerDetailBO;
import com.jt.www.domain.enums.pc.MarketerStatusEnum;
import com.jt.www.domain.po.MarketerInfoEntity;
import com.jt.www.domain.qo.MarketerInfoQO;
import com.jt.www.domain.qo.MarketerUpdQO;
import com.jt.www.model.reps.GenericDataResponse;
import com.jt.www.model.reps.GenericListResponse;
import com.jt.www.util.JsonUtil;
import com.jt.www.util.excel.CsvExportUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.assertj.core.util.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(value = "营销人员相关接口", tags = {"MARKETER-INFO-API"}, description = "营销人员相关接口")
@RestController
@RequestMapping(value = "/marketer")
public class MarketerInfoController {

    public static final Logger log = LoggerFactory.getLogger(MarketerInfoController.class);

    @Autowired
    private MarketerInfoService marketerInfoService;

    /**
     * 根据ID查询营销人员信息
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "根据ID查询营销人员信息", notes = "根据ID查询营销人员信息", httpMethod = "GET")
    @GetMapping(value = "/queryMarketerById", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public ResponseEntity queryMarketerById(@ApiParam(value = "主键id", required = true) @RequestParam("id") String id) {

        String findCode = "queryMarketerById_" + System.currentTimeMillis();

        log.info("{} 根据ID查询营销人员信息 入参：id->{}", findCode, id);

        return marketerInfoService.queryMarketerById(findCode, id);
    }

    /**
     * 营销人员配置
     *
     * @param marketerUpdQO
     * @return
     */
    @ApiOperation(value = "营销人员配置", notes = "营销人员配置", httpMethod = "POST")
    @PostMapping(value = "/updateMarketer", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public ResponseEntity updateMarketer(@RequestBody MarketerUpdQO marketerUpdQO) {

        String findCode = "updateMarketer_" + System.currentTimeMillis();

        log.info("{} 营销人员配置 入参：marketerUpdQO->{}", findCode, JsonUtil.object2Json(marketerUpdQO));

        return marketerInfoService.updateMarketer(findCode, marketerUpdQO);
    }

    /**
     * 根据条件查询营销人员列表
     *
     * @param roleCode
     * @return
     */
    @ApiOperation(value = "根据条件查询营销人员列表", notes = "根据条件查询营销人员列表", httpMethod = "GET")
    @GetMapping(value = "/queryMarketersBy", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public ResponseEntity queryMarketersBy(@ApiParam(value = "角色编码", required = true) @RequestParam("roleCode") String roleCode) {

        String findCode = "queryMarketersBy_" + System.currentTimeMillis();

        log.info("{} 根据条件查询营销人员列表 入参：roleCode->{}", findCode, roleCode);

        List<MarketerInfoEntity> list = marketerInfoService.queryMarketersBy(findCode, roleCode);

        return GenericListResponse.listAndCount(list, list.size());
    }

    /**
     * 分页查询营销人员信息
     *
     * @param marketerInfoQO
     * @return
     */
    @ApiOperation(value = "查询营销人员列表", notes = "查询营销人员列表", httpMethod = "POST")
    @PostMapping(value = "/queryMarketers", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public ResponseEntity<GenericListResponse<MarketerInfoEntity>> queryMarketers(@RequestBody MarketerInfoQO marketerInfoQO) {

        String findCode = "queryMarketers_" + System.currentTimeMillis();

        log.info("{} 查询营销人员列表 入参：marketerQO->{}", findCode, JsonUtil.object2Json(marketerInfoQO));

        if (null == marketerInfoQO || StringUtils.isBlank(marketerInfoQO.getUserCode())) {
            return GenericListResponse.listNoCount(GenericListResponse.CODE_NG, "当前操作人用户编码不能为空!", Lists.newArrayList());
        }
        PageInfo result = marketerInfoService.queryMarketers(findCode, marketerInfoQO, true);

        return GenericListResponse.listAndCount(result.getList(), result.getTotal());
    }

    /**
     * 导出营销人员信息
     *
     * @param response
     * @param marketerInfoQO
     */
    @ApiOperation(value = "导出营销人员列表", notes = "导出营销人员列表")
    @GetMapping(value = "/exportMarketers")
    public void exportMarketers(HttpServletResponse response, MarketerInfoQO marketerInfoQO) {
        try {

            String findCode = "exportMarketers_" + System.currentTimeMillis();

            log.info("{} 导出营销人员列表 入参：marketerInfoQO->{}", findCode, JsonUtil.object2Json(marketerInfoQO));

            // 查询需要导出的数据
            List<MarketerInfoEntity> list = marketerInfoService.exportMarketers(findCode, marketerInfoQO);

            // 构造导出数据结构
            String titles = "序号,营销人员工号,营销人员姓名,营销人员手机号码,专属渠道,所属机构,所属部门,地区产品营销角色,所属组长,授权业务范围,增员渠道,营销人员状态";  // 设置表头
            String keys = "serialNo,marketerNo,marketerName,marketerPhone,channelName,branchName,departName,roleName,leaderName,businessScope,addChannelName,status";  // 设置每列字段

            // 构造导出数据
            List<Map<String, Object>> datas = new ArrayList<>();
            Map<String, Object> map = null;

            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    map = new HashMap<>();
                    map.put("serialNo", i + 1);
                    map.put("marketerNo", list.get(i).getMarketerNo() + "\t");
                    map.put("marketerName", StringUtils.isNotBlank(list.get(i).getMarketerName()) ? list.get(i).getMarketerName() : "");
                    map.put("marketerPhone", list.get(i).getMarketerPhone());
                    map.put("channelName", list.get(i).getChannelName());
                    map.put("branchName", list.get(i).getBranchName());
                    map.put("departName", StringUtils.isNotBlank(list.get(i).getDepartName()) ? list.get(i).getDepartName() : "");
                    //map.put("marketerEmail", StringUtils.isNotBlank(list.get(i).getMarketerEmail())?list.get(i).getMarketerEmail():"");
                    map.put("roleName", StringUtils.isNotBlank(list.get(i).getRoleName()) ? list.get(i).getRoleName() : "");
                    map.put("leaderName", StringUtils.isNotBlank(list.get(i).getLeaderName()) ? list.get(i).getLeaderName() : "");
                    map.put("businessScope", StringUtils.isNotBlank(list.get(i).getBusinessScope()) ? list.get(i).getBusinessScope() : "");
                    map.put("addChannelName", StringUtils.isNotBlank(list.get(i).getAddChannelName()) ? list.get(i).getAddChannelName() : "");
                    map.put("status", MarketerStatusEnum.getMsgByCode(list.get(i).getStatus()));

                    datas.add(map);
                }
            }

            // 设置导出文件前缀
            String fName = "营销人员_";

            // 文件导出
            OutputStream os = response.getOutputStream();
            CsvExportUtil.responseSetProperties(fName, response);
            CsvExportUtil.doExport(datas, titles, keys, os);
            os.close();
        } catch (Exception e) {
            log.error("推广关系 导出失败" + e.getMessage(), e);
        }
    }


    /**
     * 查询营销员详情(带佣金配置相关信息)
     *
     * @param marketerNo
     * @return
     */
    @ApiOperation(value = "查询营销员详情", notes = "查询营销员详情(带佣金配置团队相关信息)", httpMethod = "POST")
    @PostMapping(value = "/queryMarketerDetails/{marketerNo}", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public ResponseEntity<GenericDataResponse<MarketerDetailBO>> queryMarketerDetails(@PathVariable("marketerNo") String marketerNo) {

        return marketerInfoService.queryMarketerDetails(marketerNo);
    }

}
